package com.project.dao.impl;

import com.project.bean.CutPageBean;
import com.project.bean.ProductBean;
import com.project.dao.IProductDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;

@Repository
public class ProductDaoImpl extends BaseDao implements IProductDao {
    @Override
    public CutPageBean<ProductBean> findByItem(int pageNO, String name) {
        CutPageBean<ProductBean> cutBean = new CutPageBean<>();
        String sql = "SELECT  p.*,COUNT(s.`pk_speakId`) speakNum FROM t_product p LEFT JOIN t_speak s " +
                "ON p.`pk_productId`=s.`fk_productId`" ;
        String dynaSql = " WHERE 1=1 ";
        if(name != null && name.length() != 0){
            dynaSql += "and p_name like '%"+name+"%' ";
        }

        this.setConnection();
        try {
            ps = con.prepareStatement(sql+dynaSql + " GROUP BY p.`pk_productId` LIMIT ?,? ");
            ps.setObject(1,(pageNO - 1)*CutPageBean.PAGESIZE);
            ps.setObject(2,CutPageBean.PAGESIZE);

            rs = ps.executeQuery();
            while(rs.next()){
                cutBean.getList().add(this.getProduct());
            }

            ps = con.prepareStatement("select count(*) c from t_product "+dynaSql);
            rs = ps.executeQuery();
            if(rs.next()) {
                cutBean.setCount(rs.getInt("c"));
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            this.closeConnection();
        }


        return cutBean;
    }

    private ProductBean getProduct() throws SQLException {
        ProductBean product = new ProductBean();
        product.setId(rs.getInt("pk_productId"));
        product.setName(rs.getString("p_name"));
        product.setPrice(rs.getInt("p_price"));
        product.setImgPath(rs.getString("p_imgPath"));
        product.setSpeakNum(rs.getInt("speakNum"));
        return product;
    }

    @Override
    public ProductBean findById(Integer id) {
        ProductBean product = null;
        this.setConnection();
        try {
            ps = con.prepareStatement("SELECT  p.*,COUNT(s.`pk_speakId`) speakNum FROM t_product p LEFT JOIN t_speak s " +
                    "ON p.`pk_productId`=s.`fk_productId` WHERE p.pk_productId=?");
            ps.setObject(1,id);
            rs = ps.executeQuery();
            if(rs.next()){
                product = this.getProduct();
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally{
            this.closeConnection();
        }

        return product;
    }
}
